import React, { useEffect, useState } from "react";
import Lottie from "@/components/Lottie";
import LoginLottie from "@/assets/lotties/login-lottie.json";
import DarkSwitch from "@/components/DarkSwitch";
import Logo from "@/assets/images/logo.png";
import { CheckCircleFilled, LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Checkbox, Form, Input, message } from "antd";
import { notification } from "@/hooks/modules/useToast";
import { Request } from "@/services/request";
import { useNavigate } from "react-router";
import { getTimeState } from "@/utils";
import { useUserStore } from "@/store/user";
import { useShallow } from "zustand/react/shallow";
import { getCookieValue, removeCookieValue, setCookieToken, setCookieValue } from "@/utils/cookies";
import { usePermissions } from "@/hooks/modules/usePermissions";

const Login: React.FC = () => {
  const { setToken } = useUserStore(useShallow((state) => ({ setToken: state.setToken })));

  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();

  const navigate = useNavigate();

  const { initPermissions } = usePermissions();

  const onFinish = async (values: { username: string; password: string; remember: boolean }) => {
    try {
      setLoading(true);
      message.open({ key: "loadKey", type: "loading", content: "登录中..." });
      const resp = await Request.get("/login", { username: values.username, password: values.password });
      setCookieToken(resp.data.token);
      setToken(resp.data.token);
      await initPermissions(resp.data.token);
      setTimeout(() => {
        notification.success({
          message: getTimeState(),
          description: `欢迎登录 ${resp.data.userInfo.name}`,
          icon: <CheckCircleFilled style={{ color: "#73d13d" }} />
        });
      }, 300);
      !values.remember && removeCookieValue("REACT_APP_USER_INFO");
      values.remember && setCookieValue("REACT_APP_USER_INFO", JSON.stringify(values), 365);
      navigate("/home", { replace: true });
    } finally {
      setLoading(false);
      message.destroy("loadKey");
    }
  };

  useEffect(() => {
    getCookieValue("REACT_APP_USER_INFO") && form.setFieldsValue(JSON.parse(getCookieValue("REACT_APP_USER_INFO") as string));
  }, []);

  return (
    <div className="w-full h-[100dvh] relative overflow-hidden bg-white dark:bg-[#293146]">
      {/*背景图*/}
      <div className="w-full h-full absolute bg-[url(@/assets/images/login-bg.svg)] dark:bg-[url(@/assets/images/login-bg-dark.svg)] bg-position-[100%] bg-size-[auto_100%] bg-no-repeat ml-[-48%]"></div>
      {/*右上角黑暗模式切换按钮*/}
      <DarkSwitch className="absolute z-50 top-[20px] right-[40px] enter-x" />
      {/*左上logo*/}
      <div className="absolute flex items-center mt-[20px] enter-x-negative">
        <img src={Logo} alt="logo" className="w-[48px] ml-[40px]" />
        <span className="text-white text-[24px] ml-[10px]">{import.meta.env.VITE_APP_TITLE}</span>
      </div>
      <div className="w-full h-full m-[0_auto] flex items-center lt-xl:justify-center">
        {/*主区域*/}
        <div className="xl:w-6/12 flex justify-center pr-[100px] enter-x-negative">
          <Lottie animationData={LoginLottie} className="md:w-[90%] lt-xl:hidden" />
        </div>
        {/*登录表单*/}
        <div className="lt-xl:absolute flex flex-col lt-xl:w-6/10 xl:w-6/12 lt-xl:bg-white lt-xl:dark:bg-[rgba(44,52,74,.8)] lt-xl:dark:shadow-2xl lt-xl:rounded-2xl lt-xl:shadow-2xl lt-xl:p-[50px] pl-[100px] enter-x">
          <span className="text-[26px] text-black dark:text-white font-bold">登录</span>
          <div className="ml-[10px] mt-[20px] xl:max-w-2/3 2xl:max-w-2/4">
            <Form name="loginForm" size="large" form={form} className="enter-x" initialValues={{ remember: true }} validateTrigger={["onBlur", "onChange"]} onFinish={onFinish}>
              <Form.Item name="username" rules={[{ required: true, message: "请输入用户名" }]}>
                <Input placeholder="请输入用户名" prefix={<UserOutlined />} />
              </Form.Item>
              <Form.Item name="password" rules={[{ required: true, message: "请输入密码" }]}>
                <Input.Password placeholder="请输入密码" prefix={<LockOutlined />} />
              </Form.Item>
              <Form.Item>
                <div className="flex justify-between items-center [&_.ant-btn]:p-0!">
                  <Form.Item name="remember" valuePropName="checked" noStyle>
                    <Checkbox>记住我</Checkbox>
                  </Form.Item>
                  <Button type="link" size="small">
                    忘记密码？
                  </Button>
                </div>
              </Form.Item>
              <Form.Item>
                <Button block loading={loading} type="primary" htmlType="submit">
                  登录
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
